package com.hdax.dm.listener;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.annotation.Id;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

/**
 * Redis监听key过期事件
 */
@Configuration
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    //订单超过15分钟进行回滚
    public void onMessage(Message message,byte[] pattern){

        //获取单号
        String orderNoStr;
        String[] split = null;
        String orderNo;

        if (message.toString() != null && !message.toString().equals("")){
            orderNoStr = message.toString();
            split = orderNoStr.split(":");
        }

        //判断订单是否过期
        if (!"orderNo".equals(split[0])){
            return;
        }

        //使用rabbitMQ进行事务回滚
        rabbitTemplate.convertAndSend("dm_order_cancel",message.toString());

    }

}
